package com.huey.concurrency;

import com.huey.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * ┃　　　┃ 神兽保佑
 * ┃　　　┃ 代码无BUG！
 * ┃　　　┗━━━┓
 * ┃　　　　　　　┣┓
 * ┃　　　　　　　┏┛
 * ┗┓┓┏━┳┓┏┛
 * ┃┫┫　┃┫┫
 * ┗┻┛　┗┻┛
 *
 * @author huey
 * @Description : 代码模拟线程安全问题
 * @Date Created in 2018/8/31 13:20
 */

@NotThreadSafe
@Slf4j
public class ConcurrencyTest {

    /**
     * 线程总数
     */
    public static final int ThreadTotal = 5000;
    /**
     * 线程并发数
     */
    public static final int CurrentTotal = 200;

    /**
     * 统计个数
     */
    public static int count = 0;

    public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(CurrentTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(ThreadTotal);

        for (int i = 0; i < ThreadTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exeception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}", count);
    }

    /**
     * @author huey
     * @Description : 并发存在问题类
     * @Date Created in 2018/8/31 13:26
     */
    public static int add() {
        return count++;
    }
}
